package org.jeecg.config.paramHandler.paramHandler;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.config.paramHandler.paramHandler.anno.AutoDateParam;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

public class AutoDateParamArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(AutoDateParam.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        String dateString = webRequest.getParameter(Objects.requireNonNull(parameter.getParameterName()));
        AutoDateParam parameterAnnotation = parameter.getParameterAnnotation(AutoDateParam.class);
        assert parameterAnnotation != null;
        Class<?> clazz = parameterAnnotation.value();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(parameterAnnotation.format());
        if (dateString == null) {
            if (parameterAnnotation.required()) {
                throw new RuntimeException("参数" + parameter.getParameterName() + "不能为空");
            } else if (parameterAnnotation.nowIfNull()) {
                return parseParam(null, clazz, formatter);
            } else return null;
        } else if (StringUtils.isBlank(dateString.trim())) {
            return null;
        } else {
            return parseParam(dateString, clazz, formatter);
        }
    }

    private Object parseParam(String dateString, Class<?> clazz, DateTimeFormatter formatter) {
        if (dateString == null) {
            dateString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        if (clazz == LocalDate.class) {
            try {
                dateString = dateString.substring(0, 10);
            } catch (Exception ignore) {
            }
            return LocalDate.parse(dateString, formatter);
        } else if (clazz == LocalDateTime.class) {
            try {
                if (dateString.length() <= 10) dateString += " 00:00:00";
            } catch (Exception ignore) {
            }
            return LocalDateTime.parse(dateString, formatter);
        }
        throw new RuntimeException("不支持的日期参数类型");
    }

}